package coupon_logic

import (
	"time"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
)

// GetUserCouponStat 获取用户优惠券统计
func (l *CouponLogic) GetUserCouponStat(req *dto.CouponUserStatReq) (*dto.CouponUserStatResp, error) {
	where := "user_id = ?"
	var params []interface{}
	params = append(params, req.UserId)

	// 处理时间范围
	if req.StartTime != "" && req.EndTime != "" {
		where += " AND create_time BETWEEN ? AND ?"
		params = append(params, req.StartTime, req.EndTime)
	}

	// 统计总领取数量
	totalReceived, err := models.Count(l.Ctx, &models.UserCoupon{}, where, params...)
	if err != nil {
		return nil, err
	}

	// 统计已使用数量
	whereUsed := where + " AND status = ?"
	paramsUsed := append([]interface{}{}, params...)
	paramsUsed = append(paramsUsed, models.CouponStatusUsed)
	totalUsed, err := models.Count(l.Ctx, &models.UserCoupon{}, whereUsed, paramsUsed...)
	if err != nil {
		return nil, err
	}

	// 统计已过期数量
	whereExpired := where + " AND status = ?"
	paramsExpired := append([]interface{}{}, params...)
	paramsExpired = append(paramsExpired, models.CouponStatusExpired)
	totalExpired, err := models.Count(l.Ctx, &models.UserCoupon{}, whereExpired, paramsExpired...)
	if err != nil {
		return nil, err
	}

	// 统计可用数量
	now := time.Now()
	whereAvailable := where + " AND status = ? AND valid_end > ?"
	paramsAvailable := append([]interface{}{}, params...)
	paramsAvailable = append(paramsAvailable, models.CouponStatusUnused, now)
	available, err := models.Count(l.Ctx, &models.UserCoupon{}, whereAvailable, paramsAvailable...)
	if err != nil {
		return nil, err
	}

	// 统计总优惠金额
	var totalDiscount int64
	whereLogs := "user_id = ? AND type = ?"
	var logs []*models.CouponLog
	err = models.Find(l.Ctx, &logs, whereLogs, req.UserId, models.CouponLogTypeUse)
	if err != nil {
		return nil, err
	}
	for _, log := range logs {
		totalDiscount += log.Discount
	}

	return &dto.CouponUserStatResp{
		TotalReceived: totalReceived,
		TotalUsed:     totalUsed,
		TotalExpired:  totalExpired,
		Available:     available,
		TotalDiscount: totalDiscount,
	}, nil
}

// GetRuleCouponStat 获取优惠券规则统计
func (l *CouponLogic) GetRuleCouponStat(req *dto.CouponRuleStatReq) (*dto.CouponRuleStatResp, error) {
	where := "rule_id = ?"
	var params []interface{}
	params = append(params, req.RuleId)

	// 处理时间范围
	if req.StartTime != "" && req.EndTime != "" {
		where += " AND create_time BETWEEN ? AND ?"
		params = append(params, req.StartTime, req.EndTime)
	}

	// 统计总发放数量
	totalIssued, err := models.Count(l.Ctx, &models.UserCoupon{}, where, params...)
	if err != nil {
		return nil, err
	}

	// 统计已使用数量
	whereUsed := where + " AND status = ?"
	paramsUsed := append([]interface{}{}, params...)
	paramsUsed = append(paramsUsed, models.CouponStatusUsed)
	totalUsed, err := models.Count(l.Ctx, &models.UserCoupon{}, whereUsed, paramsUsed...)
	if err != nil {
		return nil, err
	}

	// 统计已过期数量
	whereExpired := where + " AND status = ?"
	paramsExpired := append([]interface{}{}, params...)
	paramsExpired = append(paramsExpired, models.CouponStatusExpired)
	totalExpired, err := models.Count(l.Ctx, &models.UserCoupon{}, whereExpired, paramsExpired...)
	if err != nil {
		return nil, err
	}

	// 计算使用率
	var useRate float64
	if totalIssued > 0 {
		useRate = float64(totalUsed) / float64(totalIssued) * 100
	}

	// 统计优惠金额
	var totalDiscount int64
	var logs []*models.CouponLog
	whereLogs := "type = ? AND coupon_id IN (SELECT id FROM user_coupon WHERE rule_id = ?)"
	err = models.Find(l.Ctx, &logs, whereLogs, models.CouponLogTypeUse, req.RuleId)
	if err != nil {
		return nil, err
	}
	for _, log := range logs {
		totalDiscount += log.Discount
	}

	// 计算平均优惠金额
	var avgDiscount float64
	if totalUsed > 0 {
		avgDiscount = float64(totalDiscount) / float64(totalUsed)
	}

	return &dto.CouponRuleStatResp{
		TotalIssued:   totalIssued,
		TotalUsed:     totalUsed,
		TotalExpired:  totalExpired,
		UseRate:       useRate,
		TotalDiscount: totalDiscount,
		AvgDiscount:   avgDiscount,
	}, nil
}
